package com.hzcx.app.simplechat.ui.chat;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.exceptions.HyphenateException;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.base.BaseEmptyBean;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.ui.chat.db.ChatNoticeListDao;
import com.hzcx.app.simplechat.ui.chat.dialog.ChatGroupNicknameDialog;
import com.hzcx.app.simplechat.ui.chat.event.ChatListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatMessageListRefreshEvent;
import com.hzcx.app.simplechat.ui.friend.FriendListByLableActivity;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.group.ChatGroupComplaintActivity;
import com.hzcx.app.simplechat.ui.group.ChatGroupDeleteMemberActivity;
import com.hzcx.app.simplechat.ui.group.GroupAddFriendsActivity;
import com.hzcx.app.simplechat.ui.group.GroupCreateActivity;
import com.hzcx.app.simplechat.ui.group.GroupSearchMsgActivity;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.adapter.GroupMembersSort;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MemberBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.group.bean.GroupSettingBean;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.publicui.ExpandGridView;
import com.hzcx.app.simplechat.ui.publicui.GroupQrCodeActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicConfirmDialog;
import com.hzcx.app.simplechat.ui.publicui.adapter.GroupSettingGridAdapter;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 群组聊天-设置界面
 */
public class ChatGroupSettingActivity extends BaseActivity {


    static public String GroupShowNickName = "GroupShowNickName";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_qrcode)
    TextView tvQrcode;
    @BindView(R.id.setting_group_nick_name)
    TextView settingGroupNickName;

    @BindView(R.id.setting_groupName)
    TextView settingGroupName;
    @BindView(R.id.setting_groupCustomID)
    TextView settingGroupCustomID;

    @BindView(R.id.setting_groupIntroduce)
    TextView settingGroupIntroduce;

    @BindView(R.id.setting_groupNotice)
    TextView settingGroupNotice;

    @BindView(R.id.setting_message_ignore)
    Switch settingMessageIgnore;
    @BindView(R.id.setting_message_top)
    Switch settingMmessageTop;

    @BindView(R.id.setting_group_members_show)
    TextView settingGroupMembersShow;
    @BindView(R.id.egv_avatars)
    ExpandGridView mAvatarsEgv;

    @BindView(R.id.setting_group_exit)
    TextView settingGroupExit;

    @BindView(R.id.setting_group_manager)
    TextView settingGroupManager;

    @BindView(R.id.setting_group_show_nick_name)
    Switch groupShowNickName;


//    public static String GroupInfoBeanKey = "ChatGroupSettingActivityGroupInfoBean";
//    GroupInfoBean groupInfoBean;
    public static String GroupInfoBeanKeyGroupID = "QrCodeActivity_GroupInfoBeanKeyGroupID";
    GroupInfoBean groupInfoBean;
    private String groupID;
    private ArrayList<String> memberIds;

    private GroupSettingGridAdapter mGroupSettingGridAdapter;
    private List<MembersBean> membersBeans;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_group_setting;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        tvTitle.setText("群聊信息");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //        groupInfoBean = (GroupInfoBean)getIntent().getExtras().getSerializable(ChatGroupSettingActivity.GroupInfoBeanKey);
        groupID = getIntent().getStringExtra(GroupInfoBeanKeyGroupID);
        groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
        reStatus(groupInfoBean);
        GroupModel.getGroupMemberIds(this, groupID, new BaseObserver<List<String>>() {
            @Override
            protected void onSuccess(List<String> data) {
                memberIds  = new ArrayList<>(data);
                GroupInfoBeanLiveData.updateIds(groupID,memberIds);
            }
        });
        GroupModel.getGroupInfo(this, groupID, new BaseObserver<GroupInfoBean>() {
            @Override
            protected void onSuccess(GroupInfoBean data) {
                GroupInfoBeanLiveData.update(data);
                Log.i("groupChat", "groupInfo: " + data);
                data.save();
                groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
                reStatus(groupInfoBean);
            }
        });

    }

    private void reStatus(GroupInfoBean groupInfoBean) {
        if (groupInfoBean == null) {
            return;
        }
        settingGroupName.setText(groupInfoBean.getGroup_name());
        if (groupInfoBean.getGroup_desc().isEmpty()) {
            settingGroupIntroduce.setText("未设置");
        } else {
            settingGroupIntroduce.setText(groupInfoBean.getGroup_desc());
        }

        settingGroupCustomID.setText(groupInfoBean.getCustom_number());

        if (groupInfoBean.getGroup_placard().isEmpty()) {
            settingGroupNotice.setText("未设置");
        } else {
            settingGroupNotice.setText(groupInfoBean.getGroup_placard());
        }
        if (groupInfoBean.getMy()!=null) {
            if (TextUtils.isEmpty(groupInfoBean.getMy().getGroup_member_nickname())){
                settingGroupNickName.setText("未设置");
            }else {
                settingGroupNickName.setText(groupInfoBean.getMy().getGroup_member_nickname());
            }
        } else {
            settingGroupNickName.setText("未设置");
        }

        MembersBean myBean = groupInfoBean.getMy();
        if (myBean != null) {

            if (myBean.getIs_owner().equals("Y")) {
                settingGroupExit.setText("解散此群");
            } else {
                settingGroupExit.setText("删除并退出");
            }

            if (myBean.getIs_owner().equals("Y") || groupInfoBean.getMy().getIs_admin().equals("Y")) {
                settingGroupManager.setVisibility(View.VISIBLE);
            } else {
                settingGroupManager.setVisibility(View.GONE);
            }
        }else {
            settingGroupExit.setText("删除并退出");
            settingGroupManager.setVisibility(View.GONE);
        }


        settingGroupCustomID.setText(groupInfoBean.getCustom_number());

        // 查询消息置顶情况
        EMConversation conversation = EMClient.getInstance().chatManager()
                .getConversation(groupInfoBean.getHx_groupid(), EMConversation.EMConversationType.GroupChat, true);
        settingMmessageTop.setChecked(conversation.getExtField().equals("toTop") ? true : false);

        LitePal.where("group_id=? and myUserId=?", groupInfoBean.getHx_groupid(), UserInfoUtil.getUserId() + "").findFirstAsync(GroupSettingBean.class).listen(groupSettingBean -> {

            if (groupSettingBean != null) {
                groupShowNickName.setChecked(groupSettingBean.isGroupShowNickName());
            }
        });

        // 查询消息免打扰状态
        LitePal.where("userName=?", groupInfoBean.getHx_groupid()).findAsync(ChatNoticeListDao.class).listen(new FindMultiCallback<ChatNoticeListDao>() {
            @Override
            public void onFinish(List<ChatNoticeListDao> list) {
                if(list != null && list.size() > 0){
                    settingMessageIgnore.setChecked(true);
                }
            }
        });

        if (groupInfoBean.getMembers() == null) {
            settingGroupMembersShow.setText("查看全部群成员(0)");
            return;
        }
        settingGroupMembersShow.setText("查看全部群成员(" + groupInfoBean.getMember_total() + ")");

        membersBeans = new ArrayList<>();
        membersBeans.addAll(groupInfoBean.getMembers());
        boolean showDel = false;
        if (myBean != null) {
            showDel = myBean.getIs_admin().equals("Y") || myBean.getIs_owner().equals("Y");
        }
        // 限制顶部最多显示4行： 20 = 18 + "+" + "-"
        int maxCount = showDel ? 18 : 19;
        if (membersBeans.size() > maxCount) {
            membersBeans = membersBeans.subList(0, maxCount);
        }
        mGroupSettingGridAdapter = new GroupSettingGridAdapter(this, membersBeans);
        if (showDel) {
            mGroupSettingGridAdapter.showDele = true;
        }
        mAvatarsEgv.setAdapter(mGroupSettingGridAdapter);
        mAvatarsEgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (i == membersBeans.size()) {
                    LitePal.findAllAsync(FriendBean.class, true).listen(new FindMultiCallback<FriendBean>() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onFinish(List<FriendBean> list) {
                            List<FriendBean> friends = GroupMembersSort.sortFriend(membersBeans);
                            Log.i("ChatGroupSetting", "friendList = " + friends.size());
                            Intent intent = new Intent(ChatGroupSettingActivity.this, GroupCreateActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(FriendListByLableActivity.INTENT_LIST_BUNDLE, friends.toArray());
                            intent.putExtras(bundle);
                            intent.putExtra(GroupCreateActivity.GroupCreateActivityGroupID, groupInfoBean.getGroup_id());
                            startActivity(intent);
                        }
                    });
                } else if (i == membersBeans.size() + 1) {  // 删除群成员：群主、管理员
                    List<FriendBean> list = GroupMembersSort.sortFriend(groupInfoBean.getMembers());
                    Log.i("ChatGroupSetting", "friendList = " + list.size());
                    Intent intent = new Intent(ChatGroupSettingActivity.this, ChatGroupDeleteMemberActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(FriendListByLableActivity.INTENT_LIST_BUNDLE, list.toArray());
                    intent.putExtras(bundle);
                    intent.putExtra(GroupCreateActivity.GroupCreateActivityGroupID, groupInfoBean.getGroup_id());
                    startActivity(intent);
                } else {    // 查看好友详情
                    MembersBean membersBean = membersBeans.get(i);
                    if (membersBean.getMember_id() == UserInfoUtil.getUserId()) {   // 点击的群成员是自己
                        startActivity(new Intent(ChatGroupSettingActivity.this, MineUserInfoActivity.class));
                        return;
                    }

                    LitePal.findAllAsync(FriendBean.class, true).listen(new FindMultiCallback<FriendBean>() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onFinish(List<FriendBean> list) {
                            for (FriendBean friend: list) {
                                for (FriendCityBean friendCityBean: friend.getCity()) {
                                    if (friendCityBean.getMember_id() == membersBean.getMember_id()) {  // 好友
                                        startActivity(new Intent(ChatGroupSettingActivity.this, UserInfoActivity.class)
                                                .putExtra(UserInfoActivity.INTENT_USER_ID, membersBean.getMember_id()));
                                        return;
                                    }
                                }
                            }
                            //  陌生人
                            Intent intent = new Intent(ChatGroupSettingActivity.this, AddFriendActivity.class);
                            intent.putExtra(AddFriendActivity.INTENT_USER_ID, membersBean.getMember_id());
                            intent.putExtra(AddFriendActivity.INTENT_TYPE, 2);
                            if (groupInfoBean.getProtectedswitch() == 1) {
                                intent.putExtra(AddFriendActivity.PROTECT_GROUP_MEMBER, true);
                            }
                            startActivity(intent);
                        }
                    });
                }
            }
        });
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.setting_groupName_title, R.id.setting_group_nick_name_title, R.id.tv_qrcode, R.id.tv_notice, R.id.setting_group_manager, R.id.tv_clear, R.id.setting_groupIntroduce_title,
            R.id.setting_message_ignore, R.id.setting_message_top, R.id.setting_group_members_show, R.id.setting_complaint, R.id.setting_group_show_nick_name, R.id.setting_group_exit,
            R.id.setting_group_search_message})
    public void viewOnClick(View view) {
        if (groupInfoBean == null) { return; }
        switch (view.getId()) {
            case R.id.setting_group_members_show:
                Intent intentMembers = new Intent(ChatGroupSettingActivity.this, GroupAddFriendsActivity.class);
                intentMembers.putExtra(GroupAddFriendsActivity.GroupInfoBeanKeyGroupID, groupInfoBean.getGroup_id());
                startActivity(intentMembers);
                break;

            case R.id.setting_groupName_title:
                showGroupNameDialg();
                break;

            case R.id.setting_group_nick_name_title:
                showGroupNickNameFroMeDialg();
                break;

            case R.id.tv_qrcode: // 群二维码
//                startActivity(new Intent(this, GroupQrCodeActivity.class));
                Intent intent = new Intent(this, GroupQrCodeActivity.class);
                intent.putExtra(GroupQrCodeActivity.GroupInfoBeanKeyGroupID, groupInfoBean.getGroup_id());
                startActivity(intent);
                break;

            case R.id.setting_groupIntroduce_title:   // 群介绍
                Intent intentIntroduce = new Intent(this, ChatGroupNoticeActivity.class);
                intentIntroduce.putExtra(ChatGroupNoticeActivity.typeTag, 1);
                intentIntroduce.putExtra(ChatGroupNoticeActivity.groupIDTag, groupInfoBean.getGroup_id());
                intentIntroduce.putExtra(ChatGroupNoticeActivity.valueTag, groupInfoBean.getGroup_desc());
                startActivity(intentIntroduce);
                break;

            case R.id.tv_notice: {  // 群公告设置
                Intent intentNotice = new Intent(this, ChatGroupNoticeActivity.class);
                intentNotice.putExtra(ChatGroupNoticeActivity.typeTag, 0);
                intentNotice.putExtra(ChatGroupNoticeActivity.groupIDTag, groupInfoBean.getGroup_id());
                intentNotice.putExtra(ChatGroupNoticeActivity.valueTag, groupInfoBean.getGroup_placard());
                startActivity(intentNotice);
            }
                break;

            case R.id.setting_group_manager:  // 群管理
                Intent intentGroupManager = new Intent(this, ChatGroupManagerSettingActivity.class);
                intentGroupManager.putExtra(ChatGroupManagerSettingActivity.GroupInfoBeanKeyGroupID, groupInfoBean.getGroup_id());
                startActivity(intentGroupManager);
                break;

            case R.id.setting_message_ignore: // 消息免打扰
                try {
                    ignoreMessage();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            case R.id.setting_message_top:  // 消息置顶
                messageTop();
                break;

            case R.id.setting_complaint:    // 投诉举报

                Intent intentGroupComplaint = new Intent(this, ChatGroupComplaintActivity.class);
                intentGroupComplaint.putExtra(ChatGroupComplaintActivity.ChatGroupComplaintActivityGroupInfoBean, groupInfoBean);
                startActivity(intentGroupComplaint);
                break;

            case R.id.setting_group_show_nick_name: // 显示群成员在群中的昵称
                showGroupNickName();
                break;

            case R.id.tv_clear: // 清楚聊天记录
                clearMessage();
                break;

            case R.id.setting_group_exit:
                exitGroup();
                break;

            case R.id.setting_group_search_message:
                goToSearchMessage();
                break;
        }
    }

    private void goToSearchMessage() {
        Intent intent = new Intent(this, GroupSearchMsgActivity.class);
        intent.putExtra(GroupSearchMsgActivity.GroupInfoBeanKeyGroupID, groupInfoBean.getGroup_id());
        startActivity(intent);
    }

    public final static int RESULT_CODE = 1;
    private void exitGroup() {

        if (groupInfoBean.getMy()!=null&&groupInfoBean.getMy().getIs_owner()!=null&&groupInfoBean.getMy().getIs_owner().equals("Y")) {
            showConfirmDialog("提示", "是否确定解散该群？", null, new PublicConfirmDialog.OnPublicConfirmClickListener() {
                @Override
                public void publicConfirm() {
                    showLoading();
                    GroupModel.deleteGroup(ChatGroupSettingActivity.this, groupInfoBean.getGroup_id(), new BaseObserver<BaseEmptyBean>() {
                        @Override
                        protected void onSuccess(BaseEmptyBean data) {
                            hideLoading();
                            Intent intent = new Intent();
                            setResult(RESULT_CODE, intent);
                            finish();
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            super.onFailure(e, errorMsg);
                        }
                    });
                }
            });
        } else {
            showConfirmDialog("提示", "是否确定删除并退出该群？", null, new PublicConfirmDialog.OnPublicConfirmClickListener() {
                @Override
                public void publicConfirm() {
                    showLoading();
                    GroupModel.exitGroup(ChatGroupSettingActivity.this, groupInfoBean.getGroup_id(), new BaseObserver<BaseEmptyBean>() {
                        @Override
                        protected void onSuccess(BaseEmptyBean data) {
                            Intent intent = new Intent();
                            setResult(RESULT_CODE, intent);
                            finish();
                        }
                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            super.onFailure(e, errorMsg);
                        }
                    });
                }
            });
        }
    }

    /**
     * 显示群用户设置的昵称
     */
    private void showGroupNickName() {
        LitePal.where("group_id=? and myUserId=?", groupInfoBean.getHx_groupid(), UserInfoUtil.getUserId() + "").findFirstAsync(GroupSettingBean.class).listen(groupSettingBean -> {
            if (groupSettingBean != null) {
                boolean showName = groupShowNickName.isChecked();
                groupSettingBean.setGroupShowNickName(showName);
                groupSettingBean.save();
            } else {
                GroupSettingBean settingBean = new GroupSettingBean();
                settingBean.setGroup_id(groupInfoBean.getHx_groupid());
                settingBean.setMyUserId(UserInfoUtil.getUserId() + "");
                settingBean.setGroupShowNickName(groupShowNickName.isChecked());
                settingBean.save();
            }
        });
    }

    /**
     * 群消息置顶
     */
    private void messageTop() {
        EMConversation conversation = EMClient.getInstance().chatManager()
                .getConversation(groupInfoBean.getHx_groupid(), EMConversation.EMConversationType.GroupChat, true);
        if (settingMmessageTop.isChecked()) {
            conversation.setExtField("toTop");
        } else {
            conversation.setExtField("false");
        }
//        LiveDataBus.get().with(DemoConstant.GROUP_CHANGE).postValue(EaseEvent.create(DemoConstant.GROUP_CHANGE, EaseEvent.TYPE.GROUP));
    }

    /**
     * 群消息免打扰
     */
    private void ignoreMessage() throws HyphenateException {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (settingMessageIgnore.isChecked()) {
//            ChatNoticeListDao dao = new ChatNoticeListDao(groupInfoBean.getHx_groupid());
//            dao.save();
                        List<String> onPushList = new ArrayList<>();
                        onPushList.add(groupInfoBean.getGroup_id());
                        EMClient.getInstance().pushManager().updatePushServiceForGroup(onPushList, false);
                    } else {
//            LitePal.deleteAll(ChatNoticeListDao.class, "userName=?", groupInfoBean.getHx_groupid());
                        List<String> onPushList = new ArrayList<>();
                        onPushList.add(groupInfoBean.getGroup_id());
                        EMClient.getInstance().pushManager().updatePushServiceForGroup(onPushList, true);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();

//        if (settingMessageIgnore.isChecked()) {
//            EMClient.getInstance().groupManager().asyncBlockGroupMessage(groupInfoBean.getHx_groupid(), new EMCallBack() {
//                @Override
//                public void onSuccess() {
//                    Log.i(TAG, "onSuccess: 消息免打扰设置成功");
//                }
//                @Override
//                public void onError(int code, String error) {
//                    Log.i(TAG, "onSuccess: 消息免打扰设置失败");
//                }
//                @Override
//                public void onProgress(int progress, String status) {
//                    Log.i(TAG, "onSuccess: 消息免打扰设置中...");
//                }
//            });
//        } else {
//            EMClient.getInstance().groupManager().asyncUnblockGroupMessage(groupInfoBean.getHx_groupid(), new EMCallBack() {
//                @Override
//                public void onSuccess() {
//                    Log.i(TAG, "onSuccess: 取消消息免打扰设置成功");
//                }
//                @Override
//                public void onError(int code, String error) {
//                    Log.i(TAG, "onSuccess: 取消消息免打扰设置失败");
//                }
//                @Override
//                public void onProgress(int progress, String status) {
//                    Log.i(TAG, "onSuccess: 取消消息免打扰设置中...");
//                }
//            });
//        }
    }

    /**
     * 群名称修改弹窗
     */
    private void showGroupNameDialg() {
        if (!groupInfoBean.hasAdminAuthority()) {
            String tipMsg = "只有群主和管理员才可以修改群昵称";
            showConfirmDialog("", tipMsg, "我知道了", new PublicConfirmDialog.OnPublicConfirmClickListener() {
                @Override
                public void publicConfirm() {}
            });
            return;
        }
        String originName = settingGroupName.getText().toString();
        ChatGroupNicknameDialog dialog = new ChatGroupNicknameDialog(this, originName,
                new ChatGroupNicknameDialog.OnGroupNameListener() {
                    @Override
                    public void groupName(String name) {
                        GroupModel.modifyGroupName(ChatGroupSettingActivity.this, groupInfoBean.getGroup_id(), name, new BaseObserver<BaseEmptyBean>() {
                            @Override
                            protected void onSuccess(BaseEmptyBean data) {
                                settingGroupName.setText(name);
                                groupInfoBean.setGroup_name(name);
                                LitePal.where("hx_groupid=?", groupInfoBean.getHx_groupid()).findFirstAsync(GroupInfoBean.class).listen(groupInfoBean -> {
                                    if (groupInfoBean != null) {
                                        groupInfoBean.setGroup_name(name);
                                        groupInfoBean.save();
                                    }
                                });
                            }
                            @Override
                            public void onFailure(Throwable e, String errorMsg) {
                                super.onFailure(e, errorMsg);
                                ToastUtils.show("修改失败");
                            }
                        });
                    }
                });
        dialog.show();
    }

    /**
     * 用户群昵称修改弹窗
     */
    private void showGroupNickNameFroMeDialg() {
        String originName = settingGroupNickName.getText().toString();
        ChatGroupNicknameDialog dialog = new ChatGroupNicknameDialog(this, settingGroupNickName.getText().toString(),
                new ChatGroupNicknameDialog.OnGroupNameListener() {
                    @Override
                    public void groupName(String name) {
                        GroupModel.modifyGroupNickName(ChatGroupSettingActivity.this, groupInfoBean.getGroup_id(), name, new BaseObserver<BaseEmptyBean>() {
                            @Override
                            protected void onSuccess(BaseEmptyBean data) {
                                settingGroupNickName.setText(name);
                            }
                            @Override
                            public void onFailure(Throwable e, String errorMsg) {
                                super.onFailure(e, errorMsg);
                                ToastUtils.show("修改失败");
                            }
                        });
                    }
                });
        dialog.show();
    }


    /**
     *  清除聊天记录
     */
    private void clearMessage(){
        showConfirmDialog("提示", "是否确定清除聊天记录？", null, new PublicConfirmDialog.OnPublicConfirmClickListener() {
            @Override
            public void publicConfirm() {
                showLoading();
                new Thread(() -> {
                    EMClient.getInstance().chatManager().deleteConversation(groupInfoBean.getHx_groupid(), true);
                    handler.sendEmptyMessage(HANDLER_ChatGroup_Message_DELETE);
                }).start();
            }
        });
    }

    private static final int HANDLER_ChatGroup_Message_DELETE = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == HANDLER_ChatGroup_Message_DELETE) {
                EventBus.getDefault().post(new ChatMessageListRefreshEvent());
                EventBus.getDefault().post(new ChatListRefreshEvent());
                showError("清除成功");
                hideLoading();
            }
        }
    };
}
